#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户基站停留时长统计工具

该脚本用于分析用户到达地址表，统计每个用户在白天和夜间停留时长最长的基站。
白天时间段：06:00:00 - 21:59:59
夜间时间段：22:00:00 - 05:59:59

输入：用户到达地址表.csv
输出：用户基站统计表.csv（包含用户id、白天常驻基站id、夜间常驻基站id）
"""

import csv
from collections import defaultdict
import os


def is_daytime(time_str):
    """
    判断给定时间是否属于白天时间段
    
    Args:
        time_str: 时间字符串，格式为 "HH:MM:SS"
    
    Returns:
        bool: True表示白天，False表示夜间
    """
    hour = int(time_str.split(':')[0])
    return 7 <= hour < 19


def process_user_lac_data(input_file, output_file):
    """
    处理用户到达地址数据，统计白天和夜间常驻基站
    
    Args:
        input_file: 输入CSV文件路径
        output_file: 输出CSV文件路径
    
suoyideihaohaochuli1    Returns:
        list: 包含用户基站统计结果的字典列表
    """
    print(f"正在读取数据文件：{input_file}")
    
    # 初始化统计字典
    user_stats = defaultdict(lambda: {
        'day': defaultdict(int),  # 白天各基站停留时长
        'night': defaultdict(int)  # 夜间各基站停留时长
    })
    
    record_count = 0
    error_count = 0
    
    # 读取CSV数据
    try:
        with open(input_file, 'r', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            
            # 检查必要的列
            required_columns = ['user_id', 'time', 'lac_code', 'stay_time']
            missing_columns = [col for col in required_columns if col not in reader.fieldnames]
            if missing_columns:
                print(f"缺少必要的列：{missing_columns}")
                return None
            
            # 处理每条记录
            for row in reader:
                record_count += 1
                try:
                    user_id = str(row['user_id']).strip()
                    time_str = str(row['time']).strip()
                    lac_code = str(row['lac_code']).strip()
                    stay_time = int(float(str(row['stay_time']).strip()))
                    
                    # 提取时间部分
                    if ' ' in time_str:
                        time_part = time_str.split(' ')[1]
                    else:
                        time_part = time_str
                    
                    # 判断白天还是夜间
                    period = 'day' if is_daytime(time_part) else 'night'
                    
                    # 将分钟转换为驻留时间段，计算实际驻留时长
                    # 假设到达时间为time_part，驻留stay_time分钟
                    actual_stay_time = stay_time
                    
                    # 累加对应基站停留时长
                    user_stats[user_id][period][lac_code] += actual_stay_time
                    
                except Exception as e:
                    error_count += 1
                    if error_count <= 5:  # 只显示前5个错误
                        print(f"处理第{record_count}行数据时出错：{e}")
                    continue
    
    except Exception as e:
        print(f"读取文件失败：{e}")
        return None
    
    print(f"数据读取完成，共{record_count}条记录，{error_count}条记录出错")
    
    # 生成结果列表
    results = []
    
    for user_id in sorted(user_stats.keys()):
        stats = user_stats[user_id]
        
        # 找出白天停留时长最长的基站
        day_lac = max(stats['day'].items(), key=lambda x: x[1])[0] if stats['day'] else ''
        
        # 找出夜间停留时长最长的基站
        night_lac = max(stats['night'].items(), key=lambda x: x[1])[0] if stats['night'] else ''
        
        results.append({
            'user_id': user_id,
            'day_lac': day_lac,
            'night_lac': night_lac,
            'day_total_time_minutes': sum(stats['day'].values()),
            'night_total_time_minutes': sum(stats['night'].values()),
            'day_lac_count': len(stats['day']),
            'night_lac_count': len(stats['night'])
        })
    
    # 保存结果到CSV文件
    try:
        with open(output_file, 'w', encoding='utf-8', newline='') as csvfile:
            fieldnames = ['user_id', 'day_lac', 'night_lac', 
                         'day_total_time_minutes', 'night_total_time_minutes', 
                         'day_lac_count', 'night_lac_count']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            
            writer.writeheader()
            for row in results:
                writer.writerow(row)
        
        print(f"结果已保存到：{output_file}")
        print(f"共处理了{len(results)}个用户的基站数据")
    except Exception as e:
        print(f"保存文件失败：{e}")
        return None
    
    return results


def generate_statistics_report(results):
    """
    生成统计报告
    
    Args:
        results: 用户基站统计结果列表
    
    Returns:
        dict: 统计信息字典
    """
    if not results:
        return {}
    
    total_users = len(results)
    users_with_day_lac = sum(1 for r in results if r['day_lac'] != '')
    users_with_night_lac = sum(1 for r in results if r['night_lac'] != '')
    users_with_both_lac = sum(1 for r in results if r['day_lac'] != '' and r['night_lac'] != '')
    
    # 统计最常见的基站
    day_lac_counts = defaultdict(int)
    night_lac_counts = defaultdict(int)
    
    for r in results:
        if r['day_lac']:
            day_lac_counts[r['day_lac']] += 1
        if r['night_lac']:
            night_lac_counts[r['night_lac']] += 1
    
    most_common_day_lac = max(day_lac_counts.items(), key=lambda x: x[1])[0] if day_lac_counts else None
    most_common_night_lac = max(night_lac_counts.items(), key=lambda x: x[1])[0] if night_lac_counts else None
    
    report = {
        'total_users': total_users,
        'users_with_day_lac': users_with_day_lac,
        'users_with_night_lac': users_with_night_lac,
        'users_with_both_lac': users_with_both_lac,
        'most_common_day_lac': most_common_day_lac,
        'most_common_night_lac': most_common_night_lac
    }
    
    return report


def main():
    """
    主函数
    """
    # 设置文件路径
    data_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'data')
    input_file = os.path.join(data_dir, '用户到达地址表.csv')
    output_file = os.path.join(data_dir, '用户基站统计表.csv')
    
    # 确保输出目录存在
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    
    # 处理数据
    results = process_user_lac_data(input_file, output_file)
    
    if results is not None:
        # 生成统计报告
        report = generate_statistics_report(results)
        
        print("\n=== 统计报告 ===")
        print(f"总用户数：{report.get('total_users', 0)}")
        print(f"有白天基站的用户：{report.get('users_with_day_lac', 0)}")
        print(f"有夜间基站的用户：{report.get('users_with_night_lac', 0)}")
        print(f"同时有白天和夜间基站的用户：{report.get('users_with_both_lac', 0)}")
        
        if report.get('most_common_day_lac'):
            print(f"最常见的白天基站：{report['most_common_day_lac']}")
        if report.get('most_common_night_lac'):
            print(f"最常见的夜间基站：{report['most_common_night_lac']}")
        
        # 显示前10条结果
        print("\n=== 前10条结果预览 ===")
        for i, row in enumerate(results[:10]):
            print(f"{i+1}. 用户ID: {row['user_id']}, 白天基站: {row['day_lac']}, 夜间基站: {row['night_lac']}")
    
    print("\n处理完成！")


if __name__ == "__main__":
    main()